package com.my.javaweb;

import com.my.frame.pojo.User;
import com.my.frame.service.IUserService;
import com.my.frame.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

import static java.lang.Integer.parseInt;

@WebServlet(name = "Cookie" ,urlPatterns = "/cookie")
public class CookieDemo extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取cookie

        Cookie[] cks = req.getCookies();
        if(cks != null){
            String id = "";
            for(Cookie c:cks){
                System.out.println();
                if("uid".equals(c.getName())){
                    id = c.getValue();
                    System.out.println("cookie uid ："+id);
                }
            }
            //校验uid是否存在
            if("".equals(id)){
                System.out.println("cookie uid 不存在");
                //请求转发login
                System.out.println("没有cookie账号");
                req.getRequestDispatcher("login").forward(req,resp);
                return;
            }
            else{//免密登陆
                //校验
                IUserService userService = new UserServiceImpl();
                User u = userService.checklogin(parseInt(id));
                if(u != null){
                    //重定向去菜单

                    //将数据存储到session对象中
                    HttpSession hs = req.getSession();//获取session
                    hs.setAttribute("user",u);
                    resp.sendRedirect("/Servlet/Menu.html");
                }
                else {
                    System.out.println("这个用户从数据库消失");
                    //请求转发
                    req.getRequestDispatcher("login").forward(req,resp);
                }
                return;
            }
        }
        else {
            System.out.println("没有cookie");
            //请求转发
            req.getRequestDispatcher("login").forward(req,resp);
            return;
        }
    }
}
